<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\MenuRequest;
use App\Http\Resources\MenuCollectionResource;
use App\Http\Resources\MenuResource;
use App\Models\Menu;
use Illuminate\Http\Request;

class MenuController extends Controller
{
    /**
     * 获取基础信息
     * @return mixed
     */
    public function params()
    {
        $menus = Menu::select(['id', 'label', 'level'])->get()->map(function ($menu) {
            $menu['label'] = str_repeat('├─', $menu['level'] - 1) . $menu['label'];
            return $menu;
        });

        return $this->success($menus);
    }

    /**
     * 菜单列表
     * @param Request $request
     * @return mixed
     */
    public function index()
    {
        $menus = Menu::with('children')->where('pid', 0)->get()->prepend([
            'id' => 0,
            'label' => '名称',
            'name' => '标识',
            'path' => '路径',
            'is_show' => '是否显示',
            'icon' => '图标',
            'url' => '视图',
            'ops' => '操作'
        ]);
        return $this->success(new MenuCollectionResource($menus));
    }

    /**
     * 新增菜单
     * @param MenuRequest $request
     * @return mixed
     */
    public function store(MenuRequest $request)
    {
        $data = $this->checkData($request);

        if (!is_array($data)) { // 出错了返回错误信息
            return $data;
        }
        Menu::create($data);

        return $this->created('菜单新增成功');
    }

    /**
     * 菜单详情
     * @param Menu $menu
     * @return mixed
     */
    public function show(Menu $menu)
    {
        return $this->success(new MenuResource($menu));
    }

    /**
     * 更新菜单
     * @param MenuRequest $request
     * @param Menu $menu
     * @return mixed
     */
    public function update(MenuRequest $request, Menu $menu)
    {
        $data = $this->checkData($request);

        if (!is_array($data)) { // 出错了返回错误信息
            return $data;
        }
        $menu->fill($data);
        $menu->save();

        return $this->success(new MenuResource($menu));
    }

    /**
     * 检查输入数据并返回
     * @param $request
     * @return mixed
     */
    protected function checkData($request)
    {
        $data = $request->only(['path', 'name', 'label', 'pid', 'is_show', 'icon', 'url']);

        if ($request->has('pid') && $request->pid > 0) {
            $menu = Menu::find($request->pid);

            if (empty($menu)) {
                return $this->failed('找不到父级菜单信息');
            }
        }

        return array_merge($data, ['level' => ($menu->level ?? 0) + 1]);
    }

    /**
     * 删除菜单
     * @param Menu $menu
     * @return mixed
     */
    public function destroy(Menu $menu)
    {
        try {
            if ($menu->roles()->exists()) {
                return $this->failed('请先删除该菜单下的角色');
            }
            $menu->delete();
            return $this->success('菜单删除成功');
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }
    }
}
